package commons
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getTimer;

	import commons.cache.SourceCache;

	public class MovieClipDataContainer extends EventDispatcher
	{
		private var _movieClipDataList:Array;
		private var curMovieClipData:MovieClipData;
		private var _loadFirst:Boolean;

		public function MovieClipDataContainer(mc:MovieClipData=null, loadFirst:Boolean=false)
		{
			_loadFirst=loadFirst;
			_movieClipDataList=[];

			if (mc)
			{
				for (var i:int=0; i < mc.length; i++)
				{
					_movieClipDataList[i]={key: mc.url, index: i + 1};
				}
			}
		}

		/**
		 *
		 * @param movieKey
		 * @param startIndex
		 * @param endIndex
		 *
		 */
		public function setFrameList(movieKey:String, toStartIndex:int, fromStartIndex:int, fromEndIndex:int):void
		{
			var i:int=0;

			var arr:Array=new Array();
			for (i=fromStartIndex; i <= fromEndIndex; i++)
			{
				arr.push({key: movieKey, index: i});
			}
			_movieClipDataList.splice.apply(null, [toStartIndex - 1, 0].concat(arr));

		}


		public function getbitmapFrame(index:int):BitmapFrame
		{
			//	return null;
			var bitmapFrame:BitmapFrame;
			var obj:Object=_movieClipDataList[index - 1];
			if (obj == null)
				return null;

			if (curMovieClipData && curMovieClipData.url == obj.key)
			{

			}
			else
			{
				if (curMovieClipData)
					curMovieClipData.register--;

				curMovieClipData=SourceCache.getInstance().getObject(obj.key) as MovieClipData;
				if (curMovieClipData)
				{
					dispatchEvent(new Event(Event.CHANGE));
					curMovieClipData.register++;
				}
			}

			if (curMovieClipData)
			{
				if (null == curMovieClipData.bitmapFrameList)
				{
					return null;
				}
				bitmapFrame=curMovieClipData.bitmapFrameList[obj.index - 1];
				if (bitmapFrame == null)
				{
					bitmapFrame=curMovieClipData.getbitmapFrame(obj.index);
					if (null == curMovieClipData)
					{
						return null;
					}
					else
					{
						curMovieClipData.bitmapFrameList[obj.index - 1]=bitmapFrame;
					}
				}
				if (null == curMovieClipData)
				{
					return null;
				}
				curMovieClipData.lastUserTime=getTimer();
				return bitmapFrame;
			}
			else
			{
				if (SourceCache.getInstance().isLoading(obj.key) == false)
					SourceCache.getInstance().load(obj.key, true, _loadFirst);
			}
			return null;

		}

		public function get length():int
		{
			return _movieClipDataList.length;
		}




		public function dispose():void
		{
			_movieClipDataList=null;
			if (curMovieClipData)
				curMovieClipData.register--;
			curMovieClipData=null;
		}




	}
}

